//
//  ZXHomeTableViewController.swift
//  PandaEye_Weibo
//
//  Created by Xuan Zhang on 16/6/14.
//  Copyright © 2016年 Xuan Zhang. All rights reserved.
//

import UIKit
private let identifier = "cell"
class ZXHomeTableViewController: ZXRootViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: identifier)
    }
}

//获取数据
extension ZXHomeTableViewController{
    override func loadData(){
        let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(2.0*Double(NSEC_PER_SEC)))
        if isPullUp {
            footRefreshControl.startAnimating()
            dispatch_after(delay, dispatch_get_main_queue()){
                var  temp:[Int] = []
                let end = (self.dataArray.last ?? 1000) - 1
                let from = end - 19
                for i in (from...end).reverse(){
                    temp.append(i)
                }
                self.dataArray = self.dataArray + temp
                
                self.footRefreshControl.stopAnimating()
                self.isPullUp = false
                self.tableView.reloadData()
            }
            
        } else {
            dispatch_after(delay, dispatch_get_main_queue()){
                var temp:[Int] = []
                let from = (self.dataArray.first ?? 1000) + 1
                let end = from + 19
                for i in (from...end).reverse(){
                    temp.append(i)
                }
                self.dataArray = temp+self.dataArray
                self.refreshControl.endRefreshing()
                self.tableView.reloadData()
            }
        }
        //        print(dataArray)
    }
}


//MARK: 数据源方法
extension ZXHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return dataArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
        cell.textLabel?.text = "\(dataArray[indexPath.row])"
        return cell
    }
}
//MARK:tableView 代理方法
extension ZXHomeTableViewController{
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
        if indexPath.row == dataArray.count - 1{
            isPullUp = true
            loadData()
        }
    }
}
